/**
 * ==================================================================
 * 配置项目所用到的vite插件，修改components子目录文件后，将会自动重启vite
 * ------------------------------------------------------------------
 * Author: 曹操<pgcao@qq.com>(https://gitee.com/pgcao) License MIT
 * ==================================================================
//```````````````````````````````````````````````````````````````
// 这是一个 components 子目录 vite 插件配置文件示例
//---------------------------------------------------------------
import { minifyHtml } from 'vite-plugin-html'
export default (options?: viteUserOptions): viteUserPlugins => {
    return { plugins: minifyHtml() }
}
//```````````````````````````````````````````````````````````````
 */
import type { PluginOption } from 'vite';
import fs from 'fs';
import path from 'path';
import viteCompression from 'vite-plugin-compression';

// vite plugin
export default async (options?: viteUserOptions): Promise<(PluginOption | PluginOption[])[]> => {
  //=========================================================================================
  //低版本nodejs时处理 node_modules 里的第三方依赖插件使用了链式判断运算符 ?. 和 空值合并运算符 ??
  //=========================================================================================
  const NodeVersion = parseInt(process.version.replace('v', ''));
  NodeVersion < 14 &&
    require('@babel/register')({
      presets: ['@vue/cli-plugin-babel/preset'],
      ignore: [
        function (filename: string) {
          if (!/\.(c|m)js$/.test(filename)) {
            return true;
          }
          const source = fs.readFileSync(filename, 'utf8');
          if (source.indexOf('?.') != -1 || source.indexOf('??') != -1) {
            console.log('Babel file: ', filename);
            return false;
          }
          return true;
        }
      ],
      cache: true
    });

  //=========================================================================================
  //从 components 子目录获取所有 vite 扩展插件配置自动装载进 vite plugins
  //=========================================================================================
  var vite = require('vite');
  const currentDirPath = path.resolve(__dirname, 'components');
  const plugins: (PluginOption | PluginOption[])[] = await Promise.all(
    fs.readdirSync(currentDirPath).map(async fname => {
      const filePath = path.join(currentDirPath, fname);
      const jsconfigFile = path.resolve(filePath, 'index.ts');
      if (fs.existsSync(jsconfigFile)) {
        const loadResult = await vite.loadConfigFromFile(options, jsconfigFile);
        if ('config' in loadResult && loadResult.config.plugins) {
          return loadResult.config.plugins;
        }
      }
    })
  );

  // [生产环境资源压缩，结合nginx gzip部署丝滑无比](https://github.com/alloc/vite-plugin-compress)
  options.isBuild && options.mode == 'production' && plugins.push(viteCompression());

  return plugins;
};
